package cn.ittgh.service.VerifyCode.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.ittgh.pojo.VerifyCode.VerifyImgCode;
import cn.ittgh.service.VerifyCode.VerifyImgCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyImgCodeServiceImpl implements VerifyImgCodeService {

    @Value("${verifyCode.type}")
    private String codeType;

    @Value("${spring.data.redis.verifyCodeMaxTimes}")
    private int verifyCodeMaxTimes;

    @Value("${verifyCode.img.width}")
    private int width;

    @Value("${verifyCode.img.height}")
    private int height;

    @Value("${verifyCode.img.codeCount}")
    private int codeCount;

    @Value("${verifyCode.img.circleCount}")
    private int circleCount;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public VerifyImgCode generateVerifyImgCode() {

        // 使用hutool工具包中的工具类生成图片验证码
        //参数：宽  高  验证码位数 干扰线数量
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(width, height, codeCount, circleCount);
        String codeValue = circleCaptcha.getCode();
        String imageBase64 = circleCaptcha.getImageBase64();

        // 生成uuid作为图片验证码的key
        String codeKey = UUID.randomUUID().toString().replace("-", "");

        // 将验证码存储到Redis中
        redisTemplate.opsForValue().set("user:login:" + codeType + ":" + codeKey, codeValue, verifyCodeMaxTimes, TimeUnit.MINUTES);

        // 构建响应结果数据
        VerifyImgCode validateCodeVo = new VerifyImgCode(codeKey, "data:image/png;base64," + imageBase64);
        // 返回数据
        return validateCodeVo;
    }
}
